package com.cz.fra.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.cz.fra.entity.User;
import com.cz.fra.service.AccountService;
import com.cz.fra.service.ServiceException;
import com.cz.fra.service.impl.AccountServiceImpl;

/**
 * Retrieve all those reports from database for the first time login.
 * 
 * @author victor
 *
 */
public class RetreiveUserListServlet extends HttpServlet{

	 /**
	 * Generated serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	private AccountService accountService = new AccountServiceImpl();
	
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
	     List<User> userList = null;
		try {
			userList = accountService.getUserList();
		} catch (ServiceException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	     PrintWriter out = response.getWriter();
	     JSONArray array = new JSONArray();
	     for(User r : userList){
	    	 JSONObject obj = new JSONObject();
	    	 try{
	    		 obj.put("id", r.getUserid());
	    		 obj.put("name", r.getUsername());
	    		 if(r.getProfileImg() == null){
	    			 obj.put("profileImg", "null");
	    		 } else{
	    			 obj.put("profileImg", r.getProfileImg());
	    		 }
	    	 }catch(Exception e){
	    		 e.printStackTrace();
	    	 }
	    	 array.put(obj);
	     }
	     out.write(array.toString());
	     out.flush();
	     out.close();
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		doGet(request,response);
	}
	
}
